package edu.pw.p2pclient.networking;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

import edu.pw.p2pclient.networking.messages.Message;
import edu.pw.p2pclient.networking.messages.MsgSerializer;

import android.os.Handler;
import android.util.Log;

public class UDPListenerThread extends Thread {

	private static final String TAG = "UDPListenerThread";
	public static final int BUFFER_SIZE = 1024;

	private boolean mRunning = false;
	private MsgBuffer mBuffer;
	private DatagramSocket mSocket;

	public UDPListenerThread(MsgBuffer buffer, DatagramSocket udpSocket_) {

		super();
		mBuffer = buffer;
		mSocket = udpSocket_;
	}

	@Override
	public void run() {

		Thread.currentThread().setName(TAG);
		Log.i(TAG, "Starting UDPListenerThread.");
		mRunning = true;
		try {
			byte[] buffer = new byte[BUFFER_SIZE];
			DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
			while (mRunning) {
				mSocket.receive(packet);
				Message msg = MsgSerializer.deserialize(packet.getData());
				if (!packet.getAddress()
						.equals(CommunicationService.getInstance()
								.getMyDeviceAddress())) {
					Log.i(TAG, "UDP message received.");
					msg.setSenderAddress(packet.getAddress());
					mBuffer.put(msg);
				}
			}
		} catch (IOException e) {
			Log.w(TAG, "UDPListenerThread stopping. " + e.getMessage());
		} finally {
			if (mSocket != null)
				mSocket.close();
			mRunning = false;
			Handler handler = CommunicationService.getInstance().getHandler();
			handler.sendMessage(android.os.Message.obtain(handler,
					CommunicationService.UDPLISTENER_ENDED));
			Log.i(TAG, "Ending UDPListenerThread.");
		}
	}

	@Override
	public void interrupt() {

		Log.i(TAG, "Interrupting UDPListenerThread.");
		mRunning = false;
		mSocket.close();
		super.interrupt();
	}
}
